﻿using Approve.BLL;
using Approve.Web.Helper;
using Approve.Web.Models.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Approve.Web.Models.Filter
{
    /// <summary>
    /// 用户账号登陆过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class AccountAuthorizeFilter : ActionFilterAttribute
    {
        public AccountAuthorizeFilter()
        {
        }

        /// <summary>
        /// 开始调用Action之前
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var userCode = (HttpContext.Current.Session["AccountUserCode"] ?? "").ToString().Trim();
            var userName = (HttpContext.Current.Session["AccountUserName"] ?? "").ToString().Trim();
            var loginDate = (HttpContext.Current.Session["AccountLoginDate"] ?? "").ToString().Trim();
            var isUnLogined = userCode == "" || userName == "" || loginDate == "";
            if (isUnLogined) throw ExceptionHelper.NoSignIn();

            ApproveAccount account = new ApproveAccount
            {
                UserCode = userCode,
                UserName = userName,
                LoginDate = DateTime.Parse(loginDate)
            };
            actionContext.ControllerContext.RouteData.Values[ApproveSettings.RouteDataAccountKey] = account;
            base.OnActionExecuting(actionContext);
        }
    }
}